<!-- src/views/product/pinpai/index.vue -->
<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-row>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="品牌名称">
          <el-input v-model="queryParams.name" placeholder="请输入品牌名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">查询</el-button>
          <el-button type="primary" :icon="RefreshRight" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 操作按钮 -->
    <el-row class="mb-10">
      <el-col>
        <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
        <el-button
            type="danger"
            :icon="Delete"
            @click="handleBatchDelete"
            :disabled="selectedRows.length === 0"
        >
          批量删除
        </el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-row>
      <el-table
          v-loading="loading"
          :data="brandList"
          border
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="brandName" label="品牌名称" show-overflow-tooltip width="150" />
        <el-table-column prop="brandWeb" label="品牌网站" width="250">
          <template #default="scope">
            <span>{{ scope.row.brandWeb }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="brandLogo" label="品牌Logo" width="200">
          <template #default="scope">
            <el-image
                v-if="scope.row.logo"
                :src="scope.row.logo"
                fit="contain"
                style="width: 120px; height: 60px"
                :preview-src-list="[scope.row.logo]"
            />
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="brandDesc" label="品牌描述" show-overflow-tooltip width="230" />

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <!-- 分页 -->
    <el-row>
      <el-col :span="24">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
  </div>

  <!-- 添加/编辑品牌对话框 -->
  <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      append-to-body
  >
    <el-form
        :model="brandForm"
        :rules="formRules"
        ref="brandFormRef"
        label-width="100px"
    >
      <el-form-item label="品牌名称" prop="brandName">
        <el-input v-model="brandForm.brandName" placeholder="请输入品牌名称" />
      </el-form-item>
      <el-form-item label="品牌网址" prop="brandWeb">
        <el-input v-model="brandForm.brandWeb" placeholder="请输入品牌网址" />
      </el-form-item>
      <el-form-item label="品牌Logo" prop="logo">
        <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="brandForm.logo" :src="brandForm.logo" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="品牌描述" prop="brandDesc">
        <el-input
            v-model="brandForm.brandDesc"
            type="textarea"
            placeholder="请输入品牌描述"
            :rows="3"
        />
      </el-form-item>
      <el-form-item label="类别" prop="categoryId">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-select
                v-model="brandForm.categoryId"
                placeholder="请选择一级类别"
                @change="handleCategoryChange"
                style="width: 150px"
            >
              <el-option
                  v-for="category in categoryList"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
              />
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-select
                v-model="brandForm.cateId"
                placeholder="请选择二级类别"
                :disabled="!brandForm.categoryId"
                style="width: 150px"
            >
              <el-option
                  v-for="child in getSecondCategoryOptions(brandForm.categoryId)"
                  :key="child.id"
                  :label="child.name"
                  :value="child.id"
              />
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="brandForm.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  Search,
  RefreshRight,
  Plus,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import api from '@/utils/request.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDay } from '@/utils/date.js'

// 数据列表相关
const brandList = ref([])
const loading = ref(false)
const total = ref(0)
const selectedRows = ref([])

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: '',
  status: ''
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据 - 删除 name 字段，使用 brandName
const brandForm = ref({
  id: '',
  brandName: '',
  brandWeb: '',
  logo: '',
  brandDesc: '',
  status: 1,
  categoryId: '',
  cateId: ''
})

// 表单验证规则 - 使用 brandName 而不是 name
const formRules = {
  brandName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择一级类别', trigger: 'change' }
  ],
  cateId: [
    { required: true, message: '请选择二级类别', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 表单引用
const brandFormRef = ref()

// 类别选项列表
const categoryList = ref([])

// 获取品牌列表
const getBrandList = async () => {
  loading.value = true
  try {
    const result = await api.get('/tBrand/listAll', {
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize,
      brandName: queryParams.value.name,
      isEnabled: queryParams.value.status
    })
    if (result.code === 200) {
      brandList.value = result.data.list
      total.value = result.data.total
    } else {
      ElMessage.error(result.msg || '获取品牌列表失败')
    }
  } catch (error) {
    ElMessage.error('请求失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getBrandList()
}

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    name: '',
    status: ''
  }
  getBrandList()
}

// 分页相关方法
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  queryParams.value.pageNum = 1
  getBrandList()
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getBrandList()
}

// 表格选择事件
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 获取类别列表
const getCategoryList = async () => {
  try {
    const result = await api.get('/tCategory/list1')
    if (result.code === 200) {
      categoryList.value = result.data
    }
  } catch (error) {
    ElMessage.error('获取类别列表失败')
  }
}

// 获取二级类别选项
const getSecondCategoryOptions = (categoryId) => {
  if (!categoryId) return []
  const category = categoryList.value.find(item => item.id === categoryId)
  return category ? category.children || [] : []
}

// 一级类别变化时清空二级类别
const handleCategoryChange = (value) => {
  brandForm.value.cateId = ''
}

// 新增品牌 - 使用 brandName 而不是 name
const handleAdd = () => {
  dialogTitle.value = '添加品牌'
  isEdit.value = false
  brandForm.value = {
    brandName: '',
    brandWeb: '',
    cateId: '',
    categoryId: '',
    logo: '',
    brandDesc: '',
    status: 1
  }
  dialogVisible.value = true
}

// 编辑品牌 - 将 row.name 映射到 brandName
const handleEdit = (row) => {
  dialogTitle.value = '编辑品牌'
  isEdit.value = true
  brandForm.value = {
    id: row.id,
    brandName: row.name,  // 将 row.name 赋值给 brandName
    brandWeb: row.brandWeb,
    cateId: row.cateId,
    logo: row.logo,
    brandDesc: row.brandDesc,
    status: row.status,
    categoryId: row.categoryId || ''
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  brandFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let result
        if (isEdit.value) {
          result = await api.putJson('/tBrand/update', brandForm.value)
        } else {
          result = await api.postJson('/tBrand/add', brandForm.value)
        }

        if (result.code === 200) {
          ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
          dialogVisible.value = false
          getBrandList()
        } else {
          ElMessage.error(result.msg || (isEdit.value ? '编辑失败' : '添加失败'))
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '编辑失败' : '添加失败')
      }
    }
  })
}

// 取消对话框
const cancelDialog = () => {
  dialogVisible.value = false
}

// 删除品牌
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除品牌"${row.brandName}"吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const result = await api.postJson('/tBrand/delete', [row.id])
      if (result.code === 200) {
        ElMessage.success('删除成功')
        getBrandList()
      } else {
        ElMessage.error(result.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条数据')
    return
  }

  const ids = selectedRows.value.map(row => row.id)
  ElMessageBox.confirm(`确认删除选中的${selectedRows.value.length}条品牌数据吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const result = await api.postJson('/tBrand/delete', ids)
      if (result.code === 200) {
        ElMessage.success('删除成功')
        getBrandList()
      } else {
        ElMessage.error(result.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 图片上传相关
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code === 200) {
    brandForm.value.logo = response.data.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 初始化
onMounted(() => {
  getBrandList()
  getCategoryList()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
.mb-10 {
  margin-bottom: 10px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
